package com.itc.bi.handler;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.itc.bi.constant.SystemConstant;
import com.itc.bi.entity.DatasourceEntity;
import com.itc.common.core.exception.ServiceException;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.*;

public class DatasourceJdbcPool{


    private static  Object lock = new Object();
    private static Map<Long, DruidDataSource> connMap = new HashMap<>();

    /**
     * 获取连接
     * @param entity
     */
    public static Connection get(DatasourceEntity entity,String jdbcUrl){
        Long id = entity.getId();
        DruidDataSource dataSource = null;
        try {
            if(null == id){
                Class.forName(entity.getDriver());
                return DriverManager.getConnection(jdbcUrl,entity.getUserName(),entity.getPassword());
            }else{
                if(connMap.containsKey(id)){
                    synchronized (lock){
                        return connMap.get(id).getConnection();
                    }
                }else{
                    dataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(getProperties(entity,jdbcUrl));
                    connMap.put(id,dataSource);
                    return dataSource.getConnection();
                }
            }
        }catch (Exception e){
            if(null != dataSource){
                dataSource.close();
                connMap.remove(id);
            }
            throw new ServiceException("创建连接失败,失败信息:"+e.getMessage());
        }
    }

    /**
     * 删除
     * @param id
     */
    public static void remove(Long id){
        DruidDataSource dataSource = connMap.remove(id);
        if(null != dataSource){
            dataSource.close();
        }
    }

    private static Properties getProperties(DatasourceEntity entity,String jdbc){
        String vq = "SELECT 1";
        if(SystemConstant.DATASOURCE_TYPE_ORACLE.equals(entity.getType())){
            vq = "select 1 from dual";
        }
        Properties prop = new Properties();
        prop.put("driverClassName", entity.getDriver());
        prop.put("url", jdbc);
        prop.put("username", entity.getUserName());
        prop.put("password", entity.getPassword());
        prop.put("initialSize", "1");
        prop.put("maxActive", "20");
        prop.put("minIdle", "5");
        prop.put("maxWait", "30000");
        prop.put("validationQuery", vq);
        prop.put("testOnBorrow", "false");
        prop.put("testOnReturn", "false");
        prop.put("testWhileIdle", "true");
        prop.put("druid.keepAlive", "true");
        //prop.put("init", "true");
        return prop;
    }
}
